<template>
  <div class="content">
    <el-dialog :title="title" :visible.sync="value" width="800px" append-to-body :before-close="close">
      <template v-if="!isCheck">
        <div class="handle-button">
          <el-button @click="showInspectionInfo">验房信息</el-button>
          <el-button :disabled="orderInfo.inspectionResult == 1"
                     @click="addDamagedFacilitiesByInspection"
          >从验房单导入损坏设施
          </el-button>
        </div>
        <el-form :model="form" ref="form" :rules="rules">
          <el-form-item label="房间">
            {{ this.orderInfo.houseNew ? this.orderInfo.houseNew.premisesAddress : orderInfo.premisesAddress }}
          </el-form-item>
          <el-form-item label="房屋状态" prop="houseState">
            <el-radio-group v-model="form.houseState">
              <el-radio label="1">正常</el-radio>
              <el-radio label="2">有损坏</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="损坏详情" prop="facilityDetailList" v-if="form.houseState == 2">
            <el-button @click="addfacilities" size="small">添加</el-button>
          </el-form-item>
          <el-table :data="form.facilityDetailList" style="width: 100%" v-if="form.houseState == 2">
            <el-table-column prop="name" label="损坏设施">
              <template slot-scope="scope">
                <el-form-item label="" label-width="0" :prop="'facilityDetailList.' + scope.$index + '.name'" :rules="[
                  {
                    required: true,
                    message: '请输入房屋设施',
                    trigger: 'blur',
                  },
                ]"
                >
                  <el-input v-model="form.facilityDetailList[scope.$index].name" placeholder="请输入房屋设施"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="amount1" label="赔偿金额">
              <template slot-scope="scope">
                <el-form-item label-width="0" label="" :prop="'facilityDetailList.' + scope.$index + '.price'" :rules="[
                  {
                    required: true,
                    message: '请输入赔偿金额',
                    trigger: 'blur',
                  },
                  {
                    validator:facilityPriceValidator,
                    trigger: 'blur'
                  }
                ]"
                >
                  <el-input type="number" v-model.number="form.facilityDetailList[scope.$index].price"
                            placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" style="margin-bottom: 22px"
                           @click="delfacilities(scope.$index)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </template>
      <template v-else>
        <el-descriptions title="退房信息" :column="2">
          <el-descriptions-item label="退房单号">{{
              orderInfo.checkOutOrder.checkOutOrderId
            }}
          </el-descriptions-item>
          <el-descriptions-item label="短租订单">{{
              orderInfo.orderId
            }}
          </el-descriptions-item>
          <el-descriptions-item label="退房房间">
            {{ this.orderInfo.houseNew ? this.orderInfo.houseNew.premisesAddress : orderInfo.premisesAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="入离">
            {{ orderInfo.checkInTime | formatDate("MM-DD") }}至
            {{ orderInfo.checkOutTime | formatDate("MM-DD") }}
          </el-descriptions-item>
          <el-descriptions-item label="入住时间">{{
              orderInfo.realityCheckInTime
            }}
          </el-descriptions-item>
          <el-descriptions-item label="退房时间">{{
              orderInfo.realityCheckOutTime
            }}
          </el-descriptions-item>
        </el-descriptions>
        <el-button @click="tableVisible = true">订房明细</el-button>
        <el-tooltip class="item" effect="dark"
                    content="1.退订费按预订时选择的房间进行房费计算。2.已住房费按预订或续租时选择的房间进行房费计算"
                    placement="top-start"
        >
          <div>
            <el-button type="text">费用明细</el-button>
            <i class="el-icon-info"></i>
          </div>
        </el-tooltip>
        <!--  -->

        <PriceTable :data="orderInfo" :remainingSum.sync="remainingSum" :selection.sync="priceTableSelection" :isCancal="true" :isDetail="orderInfo.orderState !== '107'" />

        <el-descriptions title="" :column="3" v-if="remainingSum>=0">
          <el-descriptions-item label="总金额">
            {{orderInfo.orderPrice + orderInfo.couponPrice}}元
          </el-descriptions-item>
          <el-descriptions-item label="优惠金额">
            {{ orderInfo.couponPrice}}元
          </el-descriptions-item>
          <el-descriptions-item label="实付金额">
            {{ orderInfo.orderPrice}}元
          </el-descriptions-item>
          <el-descriptions-item label="退还总额">
            {{ remainingSum }}元
          </el-descriptions-item>
          <el-descriptions-item label="退还路径">
            原路返回
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions title="" :column="3" v-else>
          <el-descriptions-item label="总金额">
            {{orderInfo.orderPrice + orderInfo.couponPrice}}元
          </el-descriptions-item>
          <el-descriptions-item label="优惠金额">
            {{ orderInfo.couponPrice}}元
          </el-descriptions-item>
          <el-descriptions-item label="实付金额">
            {{ orderInfo.orderPrice}}元
          </el-descriptions-item>
          <el-descriptions-item label="补缴金额">
            {{ -remainingSum }}元
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <el-radio v-model="radio" label="1">小程序支付</el-radio>
          </el-descriptions-item>
          <el-descriptions-item label="支 付 人">
            <el-radio v-model="radio" label="1">预订房间用户</el-radio>
          </el-descriptions-item>
        </el-descriptions>
      </template>

      <span slot="footer" class="dialog-footer" v-if="orderInfo.orderState == 107">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" v-if="!isCheck" @click="checkHouse">下一步</el-button>
        <el-button type="primary" v-else @click="onSubmit">确认</el-button>
      </span>
    </el-dialog>

    <el-dialog title="订房明细" :visible.sync="tableVisible" width="800px">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="premisesAddress" label="房间"></el-table-column>
        <el-table-column prop="name" label="下单方式">
          <template slot-scope="scope">
            {{ scope.row.expensesType == 1 ? '下单' : '续租' }}
          </template>
        </el-table-column>
        <el-table-column prop="rentingTime" label="入住日期"></el-table-column>
        <el-table-column prop="rentingExpenses" label="房费"></el-table-column>
      </el-table>
    </el-dialog>
    <!-- 验房信息 -->
    <InspectionOrder v-model="inspectionInfoVisible" :orderId="orderId"/>
  </div>
</template>
<script>
import {
  houseDynamic,
  getcheckingOut,
  orderInspection,
  completed,
  expensesList,
  isCheckHouse,
  getDamagedFacilities
} from '@/api/house/condition'
import { getfacilities } from '@/api/house/unmount'
import { getToken } from '@/utils/auth'
import { DateDiff } from '@/utils/common/time'

import InspectionOrder from './inspection-order'
import PriceTable from '@/views/daily-rent/checkOut/components/price-table'
import { debounce } from '@/utils'

export default {
  name: 'checkHouse',
  components: { InspectionOrder,PriceTable },
  computed: {
    customHouseName: {
      get() {
        return this.form.houseId
          ? this.form.estateName +
          this.form.buildingName +
          '栋' +
          this.form.unitName +
          '单元' +
          this.form.roomNumber +
          '房'
          : ''
      },
      set() {
      }
    },
    //赔偿金额校验
    facilityPriceValidator() {
      return (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error('赔偿金额不能小于或等于0'))
        }
        let str = value.toString()
        if (str.includes('.')) {
          let length = str.split('.')[1].length
          if (length > 2) {
            callback(new Error('赔偿金额小数点后最多保留两位'))
          }
        }
        callback()
      }
    },
    //最终费用（结算费用+优惠券金额）
    finalCost() {
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      renderDynamic: [],
      // headers: {
      //   Authorization: "Bearer " + getToken(),
      //   ["X-Tenantid"]: 1,
      // },
      dialogSelectHouseVisible: false,
      title: '验房',
      form: {
        orderId: '1',
        houseState: '1',
        facilityDetailList: []
      },
      facilitiesMap: [],
      rules: {
        houseState: [
          { required: true, message: '请选择房屋状态', trigger: 'change' }
        ],
        facilityDetailList: [
          {
            type: 'array',
            required: true,
            message: '请添加损坏设施',
            trigger: 'change'
          }
        ]
      },
      selectFacility: true,
      selection: [],
      remainingSum: 0,
      priceTableSelection: [], //价格表格选中数据
      orderInfo: {},
      isCheck: false,
      priceTabel: [],
      detailInfo: {},
      tableData: [],
      tableVisible: false,
      inspectionInfoVisible: false,
      oneProductIsSelect: [],
      radio: '1', //暂时用
      isDetail: false //价格表格是否是否为详情
    }
  },
  created() {
    //this.getInfo();
  },
  mounted() {
    //this.getPrice();
    this.getisCheckHouse()
    this.getdayPrice()
  },
  methods: {
    DateDiff: DateDiff,
    //校验是否验房
    getisCheckHouse() {
      isCheckHouse(this.orderId).then((res) => {
        this.isCheck = res.flag
        if (this.isCheck) {
          this.getPrice()
        } else {
          this.getInfo()
        }
      })
    },
    //每日房费
    getdayPrice() {
      expensesList({ orderId: this.orderId }).then((res) => {
        this.tableData = res.rows
      })
    },
    nextHandel() {
      this.getPrice()
      this.selectFacility = true
    },
    //获取设施列表
    getfacilitiesFn() {
      getfacilities().then((response) => {
        this.facilitiesMap = response.data
      })
    },
    handleRemove(index) {
      this.form.houseImgsList.splice(index, 1)
    },
    onSuccess(response, file, fileList) {
      this.form.houseImgsList.push(response.url)
    },
    //获取详情
    getInfo() {
      if (!this.orderId) return
      houseDynamic(this.orderId).then((response) => {
        this.orderInfo = response.data
      })
    },
    //查询退房金额详细信息
    getPrice() {
      getcheckingOut(this.orderId).then((res) => {
        this.orderInfo = res.data
      })
    },
    //删除设施
    delfacilities(index) {
      this.form.facilityDetailList.splice(index, 1)
    },
    //添加设施
    addfacilities() {
      this.form.facilityDetailList.push({
        name: null,
        price: null
      })
    },
    //房间选择回调
    selectHouseCb(data) {
      let houseObj = {
        changeHouseId: data.houseId, //房屋id
        changePremisesAddress: data.premisesAddress //小区地址
      }
      this.form = { ...this.form, ...houseObj }
    },
    checkHouse() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let form = this.form
          form.orderId = this.orderId
          orderInspection(form).then((res) => {
            this.getPrice()
            this.isCheck = true
          })
        }
      })
    },
    onSubmit() {
      let form = this.form
      form.orderId = this.orderId
      let refundDetailsIds = []
      // refundDetailsIds = this.selection.filter(item => item.parentKey == 'unsubscribeRefundItem').map(item => item.id)
      refundDetailsIds = this.priceTableSelection.filter(item => item.parentKey == 'unsubscribeRefundItem').map(item => item.id)
      form.refundDetailsIds = refundDetailsIds
      console.log('form', form)
      // return
      completed(form).then((res) => {
        this.$message.success('操作成功')
        this.close()
      })
    },
    //展示验房信息
    showInspectionInfo() {
      this.inspectionInfoVisible = true
    },
    //从验房单导入损坏设施
    addDamagedFacilitiesByInspection() {
      let ids = this.orderInfo.houseInspectionIds
      this.form['houseState'] = '2'
      getDamagedFacilities(ids).then(res => {
        this.form.facilityDetailList = res.data.inspectionProcessRecordList.map(item => {
          return {
            name: item.cleaningProcessName,
            price: null
          }
        })
      })
    },
    close() {
      this.$emit('input', false)
    },
  }
}
</script>
<style lang="scss" scoped>
.item-img-box {
  position: relative;
  border: 1px solid #aaaaaa;
  width: 148px;
  height: 148px;
  margin-right: 10px;
  border-radius: 4px;
  overflow: hidden;

  .up-img {
    width: 148px;
    height: 148px;
  }

  .item-delete {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 99;
    transform: translate(-50%, -50%);
    font-size: 32px;
    color: #ff4949;
    cursor: pointer;
  }
}
</style>

<style lang="scss" scoped>
</style>
